(function () {
  const HtmlWebpackPlugin = require("html-webpack-plugin");
  const CleanCSS = require("clean-css");
  const UglifyJS = require("uglify-js");

  const fs = require("fs");
  const path = require("path");

  class InlineChunkHtmlWebpackPlugin {
    constructor(options) {
		this.version = "1.0.0"
    };
    apply(compiler) {
      // 流水线上某个环节注册自己的插件
      compiler.hooks.compilation.tap(
        "InlineChunkHtmlWebpackPlugin",
        (compilation) => {
          HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(
            "InlineChunkHtmlWebpackPlugin",
            (data, cb) => {
              // data 里拿不到link的东西，所以目前看到的插件，基于data做处理的只能把script外联的注入到页面，样式不行！
              this.handleFiles();
            }
          );
        }
      );
    };
  
    handleFiles() {
      let fileName = path.resolve(__dirname, '../', '../', "src/index.html");
      let data = fs.readFileSync(fileName);
      let originHtmlStr = String(data);

      // 2.正则匹配
      let styleInlineRegex = /<link.*href=["'](.+\.css)["'].*\/\s*>/g;
      let scriptInlineRegex = /<script.*src=["'](.+\.js)["'].*><\/script>/g;
      return new Promise((resolve, reject) => {
        // 3.替换
        let result = originHtmlStr.replace(
          styleInlineRegex,
          function (style, route) {
            // console.log(style, route, "正则匹配到的，group1-第一个小括号里匹配的");
            let fullPath = path.resolve(__dirname, '../', '../', "src", route);
            // 3.1读取css
            let result = String(fs.readFileSync(fullPath));
            result = new CleanCSS().minify(result).styles;
            return '<style type="text/css">' + result + "</style>";
          }
        );
        resolve(result);

      }).then((res) => {
        let result1 = res.replace(scriptInlineRegex, function (script, route) {
          // console.log(script, route,"正则匹配到的，group1-第一个小括号里匹配的");
          let fullPath = path.resolve(__dirname, '../', '../', "src", route);
          // 3.2读取js
          let result1 = String(fs.readFileSync(fullPath));
          // 压缩参数
          let option = {
            annotations: false, // 控制注释
            compress: {},
            mangle: false, // 混淆
            output: {
              beautify: false,
              preamble: "/* 使用uglify压缩 */",
            },
          };
          result1 = UglifyJS.minify(result1, option).code;
          return (
            '<script type="text/javascript" defer="defer">' + result1 + "</script>"
          );
        });

        if (fs.existsSync("dist_webpack")) {
          const fullPath = path.resolve(__dirname, '../', '../', "dist_webpack");
          const process = require("child_process");
          process.execSync(`rm -rf ${fullPath}`);
          console.log(`历史目录删除完成!`);
          this.mkOutDir(result1);
        } else {
          this.mkOutDir(result1);
        }
      });
    };
    mkOutDir(result1) {
      fs.mkdir("dist_webpack", (err) => {
        if (err) throw err;

        let output = path.resolve(__dirname, '../', '../', "dist_webpack", "index.html");
        fs.writeFileSync(output, result1);
        console.log(`文件输出完毕！`);
      });
    };
  }
  module.exports = InlineChunkHtmlWebpackPlugin

})()